package factory

import (
	"encoding/json"
	"nd-app/pkg/logger"
	"os"

	"github.com/spf13/viper"
	"gopkg.in/yaml.v2"
)

var AppConfig *Config

func Init(configFile string) error {
	var err error
	config := Config{}
	if configFile != "" {
		content, err := os.ReadFile(configFile)
		if err != nil {
			logger.CfgLog.Errorln("Failed to read", configFile, "file:", err)
			return err
		}
		err = yaml.Unmarshal(content, &config)
		if err != nil {
			logger.CfgLog.Errorln("Failed to unmarshal globalCfg:", err)
			return err
		}
		logger.CfgLog.Infof("using config file: %s\n", configFile)
	} else {
		viper.AddConfigPath(".")
		viper.AddConfigPath("./configs")
		viper.SetConfigName("nd-app")
		viper.SetConfigType("yaml")
		err = viper.ReadInConfig()
		if err != nil {
			logger.CfgLog.Errorln("Failed to read config file:", err)
			return err
		}
		err = viper.Unmarshal(&config)
		if err != nil {
			logger.CfgLog.Errorln("Failed to unmarshal globalCfg:", err)
			return err
		}
		logger.CfgLog.Infof("using config file: %s\n", viper.ConfigFileUsed())
	}
	err = config.Validate()
	if err != nil {
		logger.CfgLog.Errorln("Invalid globalCfg:", err)
		return err
	}
	AppConfig = &config

	if s, err := json.MarshalIndent(AppConfig, "", "  "); err == nil {
		logger.CfgLog.Infoln("AppConfig:", string(s))
	}

	return err
}

func Final() error {
	AppConfig = nil
	return nil
}
